/* This file is part of swapper project
 *
 * Copyright (C) 2020 The Swapper Project Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
package com.swapper.json.spi.supports.util;

import com.swapper.json.*;
import com.swapper.json.reflect.FieldAttributes;

import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.Date;

/**
 * The {@link Date} wrapper factory.
 */
public enum DateWrapperFactory implements JsonWrapperFactory {
  INSTANCE;

  @SuppressWarnings("unchecked")
  @Override
  public <T> JsonWrapper<T> create(JsonContext context, Type type) {
    return type == Date.class ? (JsonWrapper<T>) new Wrapper(context.getGlobalDateFormat()) : null;
  }

  @SuppressWarnings({"unchecked"})
  @Override
  public <T> JsonWrapper<T> create(JsonContext context, Field field) {
    if (field.getType() == Date.class) {
      DateFormat format = FieldAttributes.findDateFormat(field);
      if (format == null) {
        format = context.getGlobalDateFormat();
      }
      return (JsonWrapper<T>) new Wrapper(format);
    }
    return null;
  }

  public static final class Wrapper implements JsonWrapper<Date> {
    private final DateFormat _format;

    public Wrapper(DateFormat format) {
      _format = format;
    }

    @Override
    public JsonValue wrap(Date value) {
      if (value == null) {
        return JsonValue.NULL;
      } else if (_format == null) {
        return JsonNumber.valueOf(value.getTime());
      } else {
        return JsonString.valueOf(_format.format(value));
      }
    }

    @Override
    public Date unwrap(JsonValue value) {
      if (JsonValue.NULL.equals(value)) {
        return null;
      } else if (_format == null) {
        return new Date(value.toLong());
      } else {
        try {
          return _format.parse(value.toString());
        } catch (ParseException e) {
          throw new JsonIOException(e);
        }
      }
    }
  }
}
